var express = require('express');
var router = express.Router();
var sqlQuery = require('../../module/sql');
var url = require('url')
var urlencode = require('urlencode')


router.get('/',async(req,res,next)=>{
    let url = req.url
    let index = url.lastIndexOf("=")  //截取从右到左第一个#的后面的字符串
    let str = url .substring(index + 1, url .length); //截取字符串
    // console.log(str)
    // console.log(urlencode.decode(str, 'utf-8'))
    let search = urlencode.decode(str, 'utf-8') //截取的文字转换格式

    let sqlStr = "select * from film where state = 1 and brief like ?"
    let result = await sqlQuery(sqlStr,"%"+[search]+"%");
    // console.log(result)
    let Nav = await getNav()
    let currentPage = Number.parseInt(req.query.page) || 1
    let sqlStr8 = "select count(film.brief) as number from film where ((film.brief) LIKE ?)"
    let result8 = await sqlQuery(sqlStr8,"%"+[search]+"%")
    let count = result8[0].number
       //总数  count
       //每页显示
    let pagesize = 6;
       //多少条也
    let page = Math.ceil(count/pagesize);
      //  let currentPage = 1; //当前页
    if(currentPage > page){
        currentPage = page;
    }
    let minItem = (currentPage * pagesize) - pagesize + 1;
    let maxItem = (currentPage * pagesize)
      //  console.log("总数",count,"-----","每页显示",pagesize,"-----","多少页",page,"-----",minItem,maxItem)
    let data=[]
    result.forEach((item,i) => {
    let itemNum = i +1;
    if(itemNum >= minItem && itemNum <= maxItem){
         //  console.log(item.id,item.filmName,i)
        data.push(item)
    }
    });
     //  return Array.from(data)
     //  console.log(data)
      const pages = {
       page,
       currentPage,
       hasPre:currentPage > 1, //上一页
       hasNext:currentPage < page //下一页
     }
    //  console.log(data)
    //  console.log(pages)


    let options = {data,Nav,pages,search,count}
    res.render('home/search',options)

})



//获取导航
async function getNav(){
  let sqlStr = 'select * from nav where state = 1'
  let result = await sqlQuery(sqlStr);
      //结果返回
  return Array.from(result);

}



module.exports = router;